import { sp } from 'cc';
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

@ccclass('SpineAnim')
export class SpineAnim extends Component {
    @property(sp.Skeleton)
    spine: sp.Skeleton = null;

    entry: sp.spine.TrackEntry = null;
    isPlay: boolean = false;
    onSpineAnimUpdate: Function = null;
    protected onLoad(): void {
        this.entry = this.spine.getCurrent(0);
        this.spine.timeScale = 0;
    }

    play(trackIndex: number, animName: string, loop: boolean) {
        this.entry = this.spine.setAnimation(trackIndex, animName, loop);
        this.setTrackTime(0);
    }

    getEndTime() {
        return this.entry.animationEnd;
    }

    getTrackTime() {
        return this.entry.trackTime;
    }

    getAnimName() {
        return this.spine.animation;
    }

    getAnimNameList() {
        return Object.keys(this.spine.skeletonData.skeletonJson[`animations`]);
    }

    getProgress() {
        let p = 0;
        const end = this.getEndTime();
        if (end) {
            const time = this.getTrackTime();
            p = time / end;
        }
        return p;
    }

    setProgress(p: number) {
        p = p > 1 ? 1 : p;
        const endTime = this.getEndTime();
        const time = endTime * p;
        this.setTrackTime(time);
    }

    setTrackTime(time: number) {
        const end = this.getEndTime();
        if (time > end) {
            time = end;
        }
        this.entry.trackTime = time;
        this.onSpineAnimUpdate && this.onSpineAnimUpdate();
    }

    update(deltaTime: number) {
        if (!this.isPlay) return;
        if (this.entry.trackTime >= this.entry.animationEnd) {
            if (this.spine.loop) {
                this.setTrackTime(0);
                this.updateAnim(deltaTime);
            }
        } else {
            this.updateAnim(deltaTime);
        }
    }

    updateAnim(deltaTime: number) {
        const nextTime = this.entry.trackTime + deltaTime;
        this.setTrackTime(nextTime);
    }
}

